import {Directive, ElementRef, DynamicComponentLoader, ComponentRef, ReflectiveInjector, Provider, ViewContainerRef} from '@angular/core';
import {ToolTipOptions} from './tooltip.interface';
import {TooltipContainer} from './tooltip-container.component';

@Directive({
    selector: '[tooltip]',
    inputs: [
        'content: tooltip',
        'placement: tooltip-placement',
        'isOpen: tooltip-is-open',
        'animation: tooltip-animation',
        'viewport: tooltip-viewport'
    ],
    host :{
        '(focusin)': 'show($event, $target)',
        '(mouseover)': 'show($event, $target)',
        '(focusout)': 'hide($event, $target)',
        '(mouseout)': 'hide($event, $target)'
    }
})
export class Tooltip {
    // input
    content: string;
    placement: string = 'top';
    isOpen: boolean;
    animation: boolean = true;
    viewport: boolean = false;

    element: ElementRef;
    loader: DynamicComponentLoader;
    container: ViewContainerRef;

    private visible: boolean = false;
    private tooltip: Promise<ComponentRef<any>>;

    constructor(el: ElementRef, ld: DynamicComponentLoader, container: ViewContainerRef) {
        this.element = el;
        this.loader = ld;
        this.container = container;
    }

    ngOnInit() {
        if (this.isOpen) {
            this.show();
        }
    }

    // 显示
    show(event?: any, target?: any) {
        if (this.visible) {
            return;
        }

        this.visible = true;

        let options = new ToolTipOptions({
            content: this.content,
            placement: this.placement,
            animation: this.animation,
            hostEl: this.element,
            appendToBody: this.viewport
        });

        let binding = ReflectiveInjector.resolve([
                new Provider(ToolTipOptions, {useValue: options})
        ]);

        this.tooltip = this.loader.loadNextToLocation(TooltipContainer, this.container, binding)
        .then((componentRef: ComponentRef<any>) => {
            return componentRef;
        });

    }

    // 隐藏
    hide(event?: any, target?: any) {
        if (!this.visible) {
            return;
        }
        this.visible = false;

        this.tooltip.then((componentRef: ComponentRef<any>) => {
            componentRef.destroy();
            return componentRef;
        });
    }
}